package com.krain.ddbb.util;

import android.content.Context;
import android.content.Intent;
import android.support.v4.util.ArrayMap;
import android.text.TextUtils;

import com.krain.corelibrary.net.NetClient;
import com.krain.corelibrary.util.JsonUtil;
import com.krain.ddbb.R;
import com.krain.ddbb.constant.Constant;
import com.krain.ddbb.constant.Keys;
import com.krain.ddbb.entity.BaseEntity;
import com.krain.ddbb.entity.BaseListEntity;
import com.krain.ddbb.entity.UpLoadBean;
import com.orhanobut.logger.Logger;

import org.androidannotations.annotations.Bean;
import org.androidannotations.annotations.EBean;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

/**
 * Class description
 *
 * @author yamin
 * @date 2015/12/9 下午 12:59
 */
@EBean
public class HttpUtil {

    private static HttpUtil mHttpUtil;

    @Bean
    BaseUtil baseUtil;

    protected Context context;


    public HttpUtil(Context context) {
        this.context = context;
    }

    public synchronized static HttpUtil getInstance(Context context) {
        if (mHttpUtil == null) {
            mHttpUtil = new HttpUtil(context);
        }
        return mHttpUtil;
    }


    public <T> T get(Class<T> cls, String methodUrl, ArrayMap<String, String> arrayMap) {
        return requestObject(HttpMethod.GET, cls, methodUrl, arrayMap);
    }


    public <T> T post(Class<T> cls, String methodUrl, ArrayMap<String, String> arrayMap) {
        return requestObject(HttpMethod.POST, cls, methodUrl, arrayMap);
    }

    private <T> T requestObject(HttpMethod httpMethod, Class<T> cls, String methodUrl, ArrayMap<String, String> arrayMap) {
        BaseEntity entity = null;
        if (httpMethod == HttpMethod.POST) {
            entity = NetClient.getInstance(context).post(BaseEntity.class, methodUrl, arrayMap);
        } else {
            entity = NetClient.getInstance(context).get(BaseEntity.class, methodUrl, arrayMap);
        }
        if (entity != null && entity.isOk()) {
            return JsonUtil.parseObject(entity.getData(), cls);
        } else if (entity != null && !entity.isOk()) {
            if (entity.getCode() .equals(Constant.TOKEN_FAILED))
                sendTokenFileBroadCase();
            else
                sendErrorMsgBroadCast(entity.getMsg());
        } else {
            sendUnknowErrorBroadCast();
        }
        return null;
    }


    public <T> BaseListEntity<T> getList(Class<T> cls, String methodUrl, ArrayMap<String, String> arrayMap) {
        try {
            String result = NetClient.getInstance(context).getResult(methodUrl, arrayMap);
            if (TextUtils.isEmpty(result)) {
                sendUnknowErrorBroadCast();
            } else {
                BaseEntity entity = JsonUtil.parseObject(result, BaseEntity.class);
                if (entity != null && entity.isOk()) {
                    String data = new JSONObject(new JSONObject(result).optString("data")).optString("list");
                    List<T> t = JsonUtil.parseList(data, cls);
                    BaseListEntity<T> baseListEntity = new BaseListEntity();
                    baseListEntity.setList(t);
                    baseListEntity.setPage(new JSONObject(new JSONObject(result).optString("data")).optInt("page"));
                    return baseListEntity;
                } else if (entity != null && !entity.isOk()) {
                    if (entity.getCode() .equals(Constant.TOKEN_FAILED))
                        sendTokenFileBroadCase();
                    else
                        sendErrorMsgBroadCast(entity.getMsg());
                } else {
                    sendUnknowErrorBroadCast();
                }

            }

        } catch (Exception e) {

        }

        return null;
    }


    public <T> List<T> postList(Class<T> cls, String methodUrl, ArrayMap<String, String> arrayMap) {
        try {
            String result = NetClient.getInstance(context).postResult(methodUrl, arrayMap);
            if (TextUtils.isEmpty(result)) {
                sendUnknowErrorBroadCast();
            } else {
                BaseEntity entity = JsonUtil.parseObject(result, BaseEntity.class);
                if (entity != null && entity.isOk()) {
                    String data = new JSONObject(new JSONObject(result).optString("data")).optString("list");
                    List<T> t = JsonUtil.parseList(data, cls);
                    return t;
                } else if (entity != null && !entity.isOk()) {
                    if (entity.getCode() .equals(Constant.TOKEN_FAILED))
                        sendTokenFileBroadCase();
                    else
                        sendErrorMsgBroadCast(entity.getMsg());
                } else {
                    sendUnknowErrorBroadCast();
                }

            }

        } catch (Exception e) {

        }

        return null;
    }

//    /**
//     * 上传图片的方法
//     * @param file
//     * @param methodUrl
//     * @return
//     */
//    public UpLoadBean uploadFile(File file, String methodUrl,String token){
//        if (file == null || !file.exists()){
//            sendErrorMsgBroadCast("文件不存在");
//            return null;
//        }
//        BaseEntity entity = null;
//        entity = NetClient.getInstance(context).uploadFile(new StringBuffer(methodUrl).append("?").append(Keys.KEY_TOKEN).append("=").append(token).toString(),file,"image",BaseEntity.class);
//        if (entity != null && entity.isOk()) {
//            return JsonUtil.parseObject(entity.getData(), UpLoadBean.class);
//        } else if (entity != null && !entity.isOk()) {
//            sendErrorMsgBroadCast(entity.getMsg());
//        } else {
//            sendUnknowErrorBroadCast();
//        }
//        return null;
//    }


    /**
     * 上传图片的方法
     *
     * @param files
     * @param methodUrl
     * @return
     */
    public List<UpLoadBean> uploadFile(ArrayList<File> files, String methodUrl, String token) {
        for (File f : files) {
            if (f == null || !f.exists()) {
                sendErrorMsgBroadCast("文件不存在");
                return null;
            }
        }
        BaseEntity entity = null;
        entity = NetClient.getInstance(context).uploadFiles(new StringBuffer(methodUrl).append("?")
                .append(Keys.KEY_TOKEN).append("=").append(token).toString(), files, "image[]", BaseEntity.class);
        if (entity != null && entity.isOk()) {
            String data = null;
            try {
                data = new JSONObject(entity.getData()).optString("image");
            } catch (JSONException e) {
                e.printStackTrace();
                Logger.e("JSONException = e=" + e.toString());
            }
            return JsonUtil.parseList(data, UpLoadBean.class);
        } else if (entity != null && !entity.isOk()) {
            if (entity.getCode() .equals(Constant.TOKEN_FAILED)) {
                sendTokenFileBroadCase();
            } else {
                sendErrorMsgBroadCast(entity.getMsg());
            }
        } else {
            sendUnknowErrorBroadCast();
        }
        return null;
    }


    /**
     * 发送未知错误的广播
     */
    private void sendUnknowErrorBroadCast() {
        Intent intent = new Intent(Constant.ACTION_HTTP_ERRORMSG);
        intent.putExtra(Keys.KEY_HTTP_MSG, context.getString(R.string.unknow_error));
        context.sendBroadcast(intent);
    }

    /**
     * 发送未知错误的广播
     */
    private void sendTokenFileBroadCase() {
        Intent intent = new Intent(Constant.TOKEN_FAILED);
        context.sendBroadcast(intent);
    }

    /**
     * 发送错误信息广播
     *
     * @param msg
     */
    private void sendErrorMsgBroadCast(String msg) {
        Intent intent = new Intent(Constant.ACTION_HTTP_ERRORMSG);
        intent.putExtra(Keys.KEY_HTTP_MSG, msg);
        context.sendBroadcast(intent);
    }

    private enum HttpMethod {
        POST, GET
    }
}
